package com.ziyueyuwen.xiniao.controller.login.dingtalk;

import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.suyeer.basic.util.HttpResUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.bean.ZyUser;
import com.ziyueyuwen.xiniao.module.UserLoginCache;
import com.ziyueyuwen.xiniao.service.UserService;
import com.ziyueyuwen.xiniao.thirdpart.util.DingTalkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ziyueyuwen.xiniao.base.BaseUtil.checkParam;
import static com.ziyueyuwen.xiniao.base.BaseUtil.saveErrorMsgAndData;
import static com.ziyueyuwen.xiniao.base.BaseUtil.saveSuccessMsgAndData;
import static com.ziyueyuwen.xiniao.util.ConstUtil.PARAM_CODE;

/**
 * @author wancheng  on 2018/12/21.
 */
@Controller
@RequestMapping("/login/ding_talk")
public class DingTalkLoginController {

    private final static Logger logger = LoggerFactory.getLogger(DingTalkLoginController.class);

    @Autowired
    UserService userService;

    @RequestMapping(value = "e_login.do",method = RequestMethod.POST)
    public void updateStudent(HttpServletRequest request,
                              HttpServletResponse response,
                              String code) {
        HttpResContent<String> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("钉钉微应用登录");
        try {
            checkParam(PARAM_CODE, code);
            // do.
            logger.info("get code : {}", code);
            OapiUserGetuserinfoResponse dingTalkUserInfo = DingTalkUtil.getUserInfo(code);
            String talkId = dingTalkUserInfo.getUserid();
            if (StringUtils.isEmpty(talkId)) {
                throw new Exception("无效的code");
            }
            ZyUser user = userService.getUserByDingTalkId(talkId);
            if (user == null) {
                throw new Exception("用户不存在!");
            }
            user.setUserPassword(null);
            hrc.setUserSession(user);
            UserLoginCache.getInstance().add(user.getUserAccount(), hrc.getSessionId());
            saveSuccessMsgAndData(hrc, hrc.getSessionId());
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }
}
